package com.fjzx.androidframe.network.uploader;


import com.fjzx.androidframe.network.ApiFactory;
import com.fjzx.androidframe.network.entity.UploadResponse;
import com.fjzx.androidframe.network.callback.UploadProgressListener;

import java.io.File;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 文件上传器
 *
 * @author xiongyongcong
 */
public class XUploader {
    private static final String MEDIA_TYPE_TEXT = "text/plain; charset=utf-8";

    /**
     * 文件上传
     *
     * @param url       服务器地址
     * @param filePath  本地文件路径
     * @param pListener 进度回调
     * @throws Exception
     */
    public static void uploadFile(String url, String filePath, final UploadProgressListener pListener) {
        final RequestBody requestBody = buildRequestBody(filePath, pListener);
        doUpload(url, requestBody, pListener);
    }

    /**
     * 文件上传
     *
     * @param url       服务器地址
     * @param filePaths 本地文件路径
     * @param pListener 进度回调
     * @throws Exception
     */
    public static void uploadFile(String url, List<String> filePaths, final UploadProgressListener pListener) {
        final RequestBody requestBody = buildRequestBody(filePaths, pListener);
        doUpload(url, requestBody, pListener);
    }

    /**
     * 文件上传
     *
     * @param url
     * @param requestBody
     * @param pListener
     */
    private static void doUpload(String url, RequestBody requestBody, final UploadProgressListener pListener) {
        UploadApi api = ApiFactory.getApiService(url, UploadApi.class);
        Call<UploadResponse> call = api.upload(url, requestBody);
        call.enqueue(new Callback<UploadResponse>() {
            @Override
            public void onResponse(Call<UploadResponse> call, Response<UploadResponse> response) {
                if (response.isSuccessful()) {
                    pListener.onSuccess(response.body());
                } else {
                    pListener.onError(new Exception("上传失败"));
                }
            }

            @Override
            public void onFailure(Call<UploadResponse> call, Throwable t) {
                t.printStackTrace();
                pListener.onError(new Exception("上传失败"));
            }
        });
    }

    /**
     * 创建文件上传请求体
     *
     * @param filePath
     * @param pListener
     * @return
     */
    private static RequestBody buildRequestBody(String filePath, UploadProgressListener pListener) {
        File file = new File(filePath);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.addFormDataPart("file", file.getName(), RequestBody.create(MultipartBody.FORM, file));
        ProgressRequestBody fileBody = new ProgressRequestBody(builder.build(), pListener);
        return fileBody;
    }

    /**
     * 创建文件上传请求体
     *
     * @param filePaths
     * @param pListener
     * @return
     */
    private static RequestBody buildRequestBody(List<String> filePaths, UploadProgressListener pListener) {
        if (filePaths == null || filePaths.isEmpty()) {
            throw new RuntimeException("cannot build MultipartBody from a empty file list");
        }
        MultipartBody.Builder builder = new MultipartBody.Builder();
        File file;
        for (String filePath : filePaths) {
            file = new File(filePath);
            builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse(MEDIA_TYPE_TEXT), file));
        }
        // 构造带进度的请求体
        ProgressRequestBody fileBody = new ProgressRequestBody(builder.build(), pListener);
        return fileBody;
    }
}
